package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.mapper.AppUserMapper;
import com.ruoyi.system.service.IAppUserService;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {

    @Resource
    private AppUserMapper appUserMapper;

    @Autowired
    protected Validator validator;

    @Autowired
    private ISysConfigService configService;

    @Override
    public List<AppUser> selectAllAppUserList() {
        return appUserMapper.selectAllAppUserList();
    };

    @Override
    public List<AppUser> selectAllAppUserListByMobile(AppUser appUser){
        return appUserMapper.selectAllAppUserListByMobile(appUser);
    };

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public AppUser selectAppUserByUserName(String userName) {
        return appUserMapper.selectAppUserByUserName(userName);
    }

    public AppUser selectAppUserByOpenId(String openId) {
        return appUserMapper.selectAppUserByOpenId(openId);
    }

    public AppUser selectAppUserByMobile(String mobile) {
        return appUserMapper.selectAppUserByMobile(mobile);
    }

    public AppUser selectAppUserById(Long userId) {
        return appUserMapper.selectAppUserById(userId);
    }

    public int insertAppUser(AppUser appUser) {
        return appUserMapper.insertAppUser(appUser);
    }

    /**
     * 修改保存用户信息
     *
     * @param appUser 用户信息
     * @return 结果
     */
    @Override
    public int updateAppUser(AppUser appUser) {
        return appUserMapper.updateAppUser(appUser);
    }

    /**
     * 密码校验
     *
     * @param password 明文
     * @param salt     盐
     * @param hashPwd  密文
     * @return boolean
     */
    public boolean checkPassword(String password, String salt, String hashPwd) {
        return hashPwd.equals(DigestUtils.md5DigestAsHex(password.concat(salt).getBytes()));
    }

    /**
     * 随即生成盐
     * 8位随机数
     *
     * @return salt 盐
     */
    private String generateSalt() {
        return RandomStringUtils.randomAlphanumeric(8);
    }

    public List<AppUser> getAppUserList(AppUser appUser) {
        return appUserMapper.selectAppUserList(appUser);
    }

    public List<AppUser> getAppUserListByIds(String ids) {
        return appUserMapper.selectAppUserListByIds(ids);
    }

    public int deleteAppUserByIds(Long[] userIds) {
        return appUserMapper.deleteAppUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importAppUser(List<AppUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.isEmpty())
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (AppUser user : userList)
        {
            try
            {
                String password = configService.selectConfigByKey("sys.user.initPassword");
                // 验证是否存在这个用户
                AppUser u = appUserMapper.selectAppUserByMobile(user.getMobile());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    appUserMapper.insertAppUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户【" + user.getNickName() + "】导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    appUserMapper.updateAppUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户【" + user.getNickName() + "】更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、客户【" + user.getNickName() + "】已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户【" + user.getNickName() + "】导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}